﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization.Json;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace BaiduFanyi
{
    public class TranslateHelp
    {
        public static TranslateResult Translate(string value)
        {
            // 原文

            string q = value;
            // 源语言
            string from = ConfigurationManager.AppSettings["from"];
            // 目标语言
            string to = ConfigurationManager.AppSettings["to"];
            // 改成您的APP ID
            string appId = ConfigurationManager.AppSettings["appId"];
            Random rd = new Random();
            string salt = rd.Next(100000).ToString();
            salt = 1435660288.ToString();
            // 改成您的密钥
            string secretKey = ConfigurationManager.AppSettings["secretKey"];
            string sign = EncryptString(appId + q + salt + secretKey);
            string url = "http://api.fanyi.baidu.com/api/trans/vip/translate?";
            url += "q=" + HttpUtility.UrlEncode(q);
            url += "&from=" + from;
            url += "&to=" + to;
            url += "&appid=" + appId;
            url += "&salt=" + salt;
            url += "&sign=" + sign;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            request.UserAgent = null;
            request.Timeout = 6000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return getObjectByJson<TranslateResult>(retString);

        }

        public static string EncryptString(string str)
        {
            MD5 md5 = MD5.Create();
            // 将字符串转换成字节数组
            byte[] byteOld = Encoding.UTF8.GetBytes(str);
            // 调用加密方法
            byte[] byteNew = md5.ComputeHash(byteOld);
            // 将加密结果转换为字符串
            StringBuilder sb = new StringBuilder();
            foreach (byte b in byteNew)
            {
                // 将字节转换成16进制表示的字符串，
                sb.Append(b.ToString("x2"));
            }
            // 返回加密的字符串
            return sb.ToString();
        }

        private static T getObjectByJson<T>(string jsonString)
        {
            // 实例化DataContractJsonSerializer对象，需要待序列化的对象类型  
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            //把Json传入内存流中保存  
            //jsonString = "[" + jsonString + "]";
            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            // 使用ReadObject方法反序列化成对象  
            object ob = serializer.ReadObject(stream);
            T ls = (T)ob;
            return ls;
        }

        public static TranslateResult Translate(string value, TranslateType translateType)
        {
            // 原文

            string q = value;
            // 源语言
            string from = ConfigurationManager.AppSettings["from"];
            // 目标语言
            string to = ConfigurationManager.AppSettings["to"];

            if (translateType == TranslateType.Eng)
            {
                from = ConfigurationManager.AppSettings["to"];
                to = ConfigurationManager.AppSettings["from"];
            }
            // 改成您的APP ID
            string appId = ConfigurationManager.AppSettings["appId"];
            Random rd = new Random();
            string salt = rd.Next(100000).ToString();
            salt = 1435660288.ToString();
            // 改成您的密钥
            string secretKey = ConfigurationManager.AppSettings["secretKey"];
            string sign = EncryptString(appId + q + salt + secretKey);
            string url = "http://api.fanyi.baidu.com/api/trans/vip/translate?";
            url += "q=" + HttpUtility.UrlEncode(q);
            url += "&from=" + from;
            url += "&to=" + to;
            url += "&appid=" + appId;
            url += "&salt=" + salt;
            url += "&sign=" + sign;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            request.UserAgent = null;
            request.Timeout = 6000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return getObjectByJson<TranslateResult>(retString);

        }

        public static TranslateResult Translate(string value, string from, string to)
        {
            // 原文

            string q = value;
            // 源语言
            // 改成您的APP ID
            string appId = ConfigurationManager.AppSettings["appId"];
            Random rd = new Random();
            string salt = rd.Next(100000).ToString();
            salt = 1435660288.ToString();
            // 改成您的密钥
            string secretKey = ConfigurationManager.AppSettings["secretKey"];
            string sign = EncryptString(appId + q + salt + secretKey);
            string url = "http://api.fanyi.baidu.com/api/trans/vip/translate?";
            url += "q=" + HttpUtility.UrlEncode(q);
            url += "&from=" + from;
            url += "&to=" + to;
            url += "&appid=" + appId;
            url += "&salt=" + salt;
            url += "&sign=" + sign;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            request.UserAgent = null;
            request.Timeout = 6000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return getObjectByJson<TranslateResult>(retString);

        }

    }

    public static class Launge
    {
        public static string 简体中文 = "zh";
        public static string 繁体中文 = "cht";
        public static string 英语 = "en";
        public static string 德语 = "de";
        public static string 西班牙语 = "spa";
        public static string 法语 = "fra";
        public static string 印地语 = "hi";
        public static string 意大利语 = "it";
        public static string 日语 = "jp";
        public static string 韩语 = "kor";
        public static string 波兰语 = "pl";
        public static string 葡萄牙语 = "pt";
        public static string 俄语 = "ru";
        public static string 土耳其语 = "tr";
        public static string 越南语 = "vie";

        /// <summary>
        ///baidu 翻译结果
        /// </summary>
        public static Dictionary<string, string> ToValues = new Dictionary<string, string>();

        /// <summary>
        /// google转换结果
        /// </summary>
        public static Dictionary<string, string> Values = new Dictionary<string, string>();

        /// <summary>
        /// key:百度翻译 Value谷歌翻译
        /// </summary>
        public static Dictionary<string,string> BaiDuToGoogle=new Dictionary<string, string>();

        public static Dictionary<string,int> BaiduIndex=new Dictionary<string, int>();

        
        static Launge()
        {
            //m_ToValues.Add(nameof(简体中文), "zh");
            ToValues.Add(nameof(繁体中文), "cht");
            ToValues.Add(nameof(英语), "en");
            ToValues.Add(nameof(德语), "de");
            ToValues.Add(nameof(西班牙语), "spa");
            ToValues.Add(nameof(法语), "fra");
            ToValues.Add(nameof(印地语), "hi");
            ToValues.Add(nameof(意大利语), "it");
            ToValues.Add(nameof(日语), "jp");
            ToValues.Add(nameof(韩语), "kor");
            ToValues.Add(nameof(波兰语), "pl");
            ToValues.Add(nameof(葡萄牙语), "pt");
            ToValues.Add(nameof(俄语), "ru");
            ToValues.Add(nameof(土耳其语), "tr");
            ToValues.Add(nameof(越南语), "vie");





            //m_Values.Add(nameof(简体中文), "zh-cn");
            Values.Add(nameof(繁体中文), "zh-tw");
            Values.Add(nameof(英语), "en-us");
            Values.Add(nameof(德语), "de-de");
            Values.Add(nameof(西班牙语), "es-es");
            Values.Add(nameof(法语), "fr-fr");
            Values.Add(nameof(印地语), "hi-in");
            Values.Add(nameof(意大利语), "it-it");
            Values.Add(nameof(日语), "ja-jp");
            Values.Add(nameof(韩语), "ko-kr");
            Values.Add(nameof(波兰语), "pl-pl");
            Values.Add(nameof(葡萄牙语), "pt-br");
            Values.Add(nameof(俄语), "ru-ru");
            Values.Add(nameof(土耳其语), "tr-tr");
            Values.Add(nameof(越南语), "vi-vn");

            int i = 0;
            foreach (KeyValuePair<string, string> keyValuePair in ToValues)
            {
                BaiDuToGoogle.Add(keyValuePair.Value, Values[keyValuePair.Key]);
                BaiduIndex.Add(keyValuePair.Value, i);
                i++;
            }
          
        }

        public static string GetValue(string value)
        {
            return Values[value];
        }
    }


    public enum TranslateType
    {
        None = 0x00,
        /// <summary>
        /// 入参英语
        /// </summary>
        Eng = 0X01,
        Chines = 0x02

    }

}